<style lang="less" scoped>
  @import "../../../styles/common.less";
</style>

<template>
  <div class="">
    <Row>
      <Col span="24">
        <Card>
          <p slot="title">
            用户更新
          </p>
          <Row>
            <Col span="24">
              <Form ref="dataInfo" :model="dataInfo" :rules="ruleInline" :label-width="80">
                <FormItem label="用户名" prop="username">
                  <Input icon="android-list" v-model="dataInfo.username"/>
                </FormItem>
                <FormItem label="用户昵称" prop="nickname">
                  <Input icon="android-list" v-model="dataInfo.nickname"/>
                </FormItem>
                <FormItem label="密码" prop="password" v-if="!updatedId">
                  <Input type="password" v-model="dataInfo.password"></Input>
                </FormItem>
                <FormItem label="重复密码" prop="re_password" v-if="!updatedId">
                  <Input type="password" v-model="dataInfo.re_password"></Input>
                </FormItem>
                <FormItem label="角色" prop="roleIds">
                  <CheckboxGroup v-model="dataInfo.roleIds">
                    <Checkbox :label="item.id" v-for="item in roleList">{{ item.title }}</Checkbox>
                  </CheckboxGroup>
                </FormItem>
                <FormItem>
                  <Button type="primary" @click="handleSubmit('dataInfo')">
                    <span v-if="!submitLoading">提交保存</span>
                    <span v-else>正在保存中...</span>
                  </Button>
                  <Button type="ghost" @click="goHistory" style="margin-left: 8px">返回</Button>
                  <Button type="ghost" @click="handleReset('dataInfo')" style="margin-left: 8px">重置</Button>
                </FormItem>
              </Form>
            </Col>
          </Row>
        </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
import util from '@/libs/util.js'
import dataApi from "@/api/system/user.js"

export default {
  name: 'system-user-edit',
  data () {
    return {
      // 更新数据编号
      updatedId: 0,
      // 表单信息
      dataInfo: {
        username: '',
        nickname: '',
        password: '',
        re_password: '',
        roleIds: []
      },
      // 提交按钮加载状态
      submitLoading: false,
      // 角色列表
      roleList: [],
      // 验证规则信息
      ruleInline: {
        username: [
          { required: true, validator: this.validateUsername, trigger: 'blur' }
        ],
        nickname: [
          { required: true, validator: this.validateNickname, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: this.validatePass, trigger: 'blur' }
        ],
        re_password: [
          { required: true, validator: this.validatePassCheck, trigger: 'blur' }
        ],
        roleIds: [
          { required: true, type: 'array', min: 1, message: '至少选择一种角色', trigger: 'change' },
          { type: 'array', max: 2, message: '最多可选择两种角色', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    validatePass (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入您的密码'))
      } else if (value.length < 6) {
        callback(new Error('密码位数必须大于6位'))
      } else {
        if (this.dataInfo.re_password !== '') {
          // 对第二个密码框单独验证
          this.$refs.dataInfo.validateField('re_password')
        }
        callback()
      }
    },
    validatePassCheck (rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dataInfo.password) {
        callback(new Error('两个输入密码不匹配'))
      } else {
        callback()
      }
    },
    validateUsername (rule, value, callback) {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      } else {
        callback()
      }
    },
    validateNickname (rule, value, callback) {
      if (!value) {
        return callback(new Error('昵称不能为空'))
      } else {
        callback()
      }
    },
    // 初始化
    init () {
      let vm = this
      return new Promise((resolve, reject) => {
        dataApi.roleList().then(
          res => {
            resolve(res)
          }
        )
      }).then(
        res => {
          vm.roleList = res.data
          if (vm.updatedId) {
            dataApi.detail(vm.updatedId).then(
              res => {
                // vm.dataInfo = res.data.detail
                vm.dataInfo.username = res.data.detail.username
                vm.dataInfo.nickname = res.data.detail.nickname
                vm.dataInfo.roleIds = res.data.roleIds
              }
            )
          }
        }
      )
    },
    handleSubmit (name) {
      let vm = this
      vm.submitLoading = true
      this.$refs[name].validate((valid) => {
        if (valid) {
          return new Promise((resolve, reject) => {
            let params = {
              formData: this.dataInfo
            }
            let result
            if (vm.updatedId) {
              result = dataApi.update(vm.updatedId, params)
            } else {
              result = dataApi.create(params)
            }
            vm.submitLoading = false
            result.then(
              res => {
                vm.$Message.success(res.msg)
                vm.$router.go(-1)
              }
            )
          })
        } else {
          vm.submitLoading = false
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    goHistory () {
      this.$router.go(-1)
    }
  },
  created () {
    var id = this.$route.query.id
    if (!(id === undefined)) {
      this.updatedId = id
    }
    //  如果有id则为更新
    this.init()
  }
}
</script>
